﻿using KingRoad.EPM.CompletionMaterialsEntity.Model;
using KingRoad.EPM.Web.Areas.CompletionMaterials.CompletionMaterialsFramework.Common;
using KingRoad.EPM.Web.Areas.CompletionMaterials.ViewModels;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace KingRoad.EPM.Web.Areas.CompletionMaterials.Controllers
{
    public class ProFileController : BaseController
    {
        /// <summary>
        /// 竣工资料查看
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 工程项目竣工资料类型 Json信息
        /// </summary>
        /// <param name="type">页面类型</param>
        /// <param name="id">项目材料类型id</param>
        /// <returns></returns>
        public JsonResult ProFileTypeJson(string id)
        {
            List<treeNodes> treenodes = new List<treeNodes>();
            if (id == null)
            {
                string sql = " Pft_PID is null and P_ID=" + PID;
                List<BcdProfiletypeInfo> pList = BcdProfiletypeUIRule.GetEntityListBySql(sql);
                foreach (BcdProfiletypeInfo pInfo in pList)
                {
                    treeNodes pnode = new treeNodes();
                    pnode.pId = "null";
                    pnode.id = pInfo.Pft_ID;
                    pnode.open = "true";
                    pnode.name = GetNodeName(pInfo.Pft_ID, 2);
                    treenodes.Add(pnode);

                    List<BcdProfiletypeInfo> pfList = BcdProfiletypeUIRule.GetEntityListBySql(" Pft_PID='" + pInfo.Pft_ID + "' ");
                    foreach (BcdProfiletypeInfo info in pfList)
                    {
                        treeNodes node = new treeNodes();
                        node.pId = info.Pft_PID;
                        node.id = info.Pft_ID;
                        node.name = GetNodeName(info.Pft_ID, 2);
                        int count = BcdProfiletypeUIRule.GetSonCountByPftID(info.Pft_ID);
                        if (count > 0)
                            node.isParent = true;
                        treenodes.Add(node);
                    }
                }
            }
            else
            {
                List<BcdProfiletypeInfo> pfList = BcdProfiletypeUIRule.GetEntityListBySql(" Pft_PID='" + id + "' ");
                foreach (BcdProfiletypeInfo info in pfList)
                {
                    treeNodes node = new treeNodes();
                    node.pId = info.Pft_PID;
                    node.id = info.Pft_ID;
                    node.name = GetNodeName(info.Pft_ID, 2);
                    int count = BcdProfiletypeUIRule.GetSonCountByPftID(info.Pft_ID);
                    if (count > 0)
                        node.isParent = true;
                    treenodes.Add(node);
                }
            }
            return Json(treenodes, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 工程项目竣工资料类型  查看
        /// </summary>
        /// <param name="tab_i">要显示的tab标签序号</param>
        /// <param name="id">材料类型</param>
        /// <returns></returns>
        public ActionResult Detail(string tab_i, string id)
        {
            ProFileTypeViewModel vm = new ProFileTypeViewModel();
            ViewBag.Tab_i = tab_i;
            ViewBag.Id = id;
            if (id != null && id != "null" && id != "")
            {
                //工程项目竣工资料类型详情
                vm.TheBcdProfiletypeInfo = BcdProfiletypeUIRule.GetEntityById(new Guid(id));
            }
            else
            {
                vm.TheBcdProfiletypeInfo = new BcdProfiletypeInfo();
            }
            return View(vm);
        }

        #region 文件材料查看
        public ActionResult VolumeList(string id)
        {
            BcdVolumeDirectoryViewModel vm = new BcdVolumeDirectoryViewModel();
            //第几页
            ViewBag.pageNum = 1;
            //每页多少条
            ViewBag.numPerPage = 20;
            ViewBag.Pft_ID = id;
            //案卷目录表
            string sql = " (Pft_ID='" + id + "' or Pft_PIds like '%" + id + "%') and Vd_State=2 ";
            int totalRecord = 0;
            //当前页码
            vm.TheBcdVolumedirectoryList = BcdVolumedirectoryUIRule.GetEntityListByContionRe(ViewBag.pageNum, ViewBag.numPerPage, "Vd_State,Vd_Order", out totalRecord, sql, "asc", "View_VolumeList");
            vm.TheBcdVolumedirectoryList.ForEach(t =>
            {
                t.FilePath = FilePath(t.Vd_ID, t.Pft_ID);
                t.FileCount = GetFilesCount(Server.MapPath(String.Format("~/Files/{0}", t.FilePath)), 0);
            });
            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            return PartialView(vm);
        }

        /// <summary>
        /// 未归档文件列表分页
        /// </summary>
        /// <returns></returns>
        public ActionResult VolumeSplitPage()
        {
            BcdVolumeDirectoryViewModel vm = new BcdVolumeDirectoryViewModel();
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = Convert.ToInt32(Request.Form["pageNum"]);
            //每页多少条
            ViewBag.numPerPage = Convert.ToInt32(Request.Form["numPerPage"]);
            ViewBag.Pft_ID = Request.Form["Pft_ID"];
            if (ViewBag.pageNum == 0 || ViewBag.numPerPage == 0)
                return VolumeList(ViewBag.FId);
            else
            {
                //工程项目与归档类型与案卷目录对应关系表
                string sql = " (Pft_ID='" + ViewBag.Pft_ID + "' or Pft_PIds like '%" + ViewBag.Pft_ID + "%') and Vd_State=2 ";
                ViewBag.iput_code = Request.Form["iput_code"];
                ViewBag.iput_name = Request.Form["iput_name"];
                if (ViewBag.iput_code != "")
                    sql += " and Vd_Code like '%" + ViewBag.iput_code + "%' ";
                if (ViewBag.iput_name != "")
                    sql += " and Vd_Name like '%" + ViewBag.iput_name + "%' ";
                //案卷目录表
                vm.TheBcdVolumedirectoryList = BcdVolumedirectoryUIRule.GetEntityListByContionRe(ViewBag.pageNum, ViewBag.numPerPage, "Vd_State,Vd_Order", out totalRecord, sql, "asc", "View_VolumeList");
                vm.TheBcdVolumedirectoryList.ForEach(t =>
                {
                    t.FilePath = FilePath(t.Vd_ID, t.Pft_ID);
                    t.FileCount = GetFilesCount(Server.MapPath(String.Format("~/Files/{0}", t.FilePath)), 0);
                });
                //总条数
                ViewBag.totalcount = totalRecord;
                //总页数
                ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            }
            return View("VolumeList", vm);
        }
        #endregion

        /// <summary>
        /// 档案管理-首页
        /// </summary>
        /// <returns></returns>
        public ActionResult ArchiveList(string id)
        {
            ArchiveViewModel vm = new ArchiveViewModel();
            ViewBag.PftId = id;
            //第几页
            ViewBag.pageNum = 1;
            //每页多少条
            ViewBag.numPerPage = 20;
            if (id != null && id != "null" && id != "")
            {
                //案卷表
                string sql = " (Pft_ID='" + id + "' or Pft_PIds like '%" + id + "%') ";
                int totalRecord = 0;
                //当前页码
                vm.TheBcdFilelistList = BcdFilelistUIRule.GetEntityListByContionRe(ViewBag.pageNum, ViewBag.numPerPage, "Fl_Numb", out totalRecord, sql, "asc", "View_FileList");
                //总条数
                ViewBag.totalcount = totalRecord;
                //总页数
                ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            }
            else
            {
                vm.TheBcdFilelistList = new List<BcdFilelistInfo>();
            }
            return PartialView(vm);
        }
        /// <summary>
        /// 案卷列表分页
        /// </summary>
        /// <returns></returns>
        public ActionResult ArchiveSplitPage()
        {
            ArchiveViewModel vm = new ArchiveViewModel();
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = Convert.ToInt32(Request.Form["pageNum"]);
            //每页多少条
            ViewBag.numPerPage = Convert.ToInt32(Request.Form["numPerPage"]);
            ViewBag.PftId = Request.Form["PftId"];

            if (ViewBag.pageNum == 0 || ViewBag.numPerPage == 0)
                return ArchiveList(ViewBag.PftId);
            else
            {
                //工程项目与归档类型与案卷目录对应关系表
                string sql = " (Pft_ID='" + ViewBag.PftId + "' or Pft_PIds like '%" + ViewBag.PftId + "%') ";
                ViewBag.iput_code = Request.Form["iput_code"];
                ViewBag.iput_numb1 = Request.Form["iput_numb1"];
                ViewBag.iput_numb2 = Request.Form["iput_numb2"];
                ViewBag.iput_name = Request.Form["iput_name"];
                if (ViewBag.iput_code != "")
                    sql += " and Fl_Code like '%" + ViewBag.iput_code + "%' ";
                if (ViewBag.iput_numb1 != "")
                {
                    if (IsNumeric(ViewBag.iput_numb1))
                        sql += " and Fl_Numb>=" + ViewBag.iput_numb1;
                }
                if (ViewBag.iput_numb2 != "")
                {
                    if (IsNumeric(ViewBag.iput_numb2))
                        sql += " and Fl_Numb<=" + ViewBag.iput_numb2;
                }
                if (ViewBag.iput_name != "")
                    sql += " and Fl_Item+Fl_FileTitle+Fl_FileName like '%" + ViewBag.iput_name + "%' ";
                //案卷目录表
                vm.TheBcdFilelistList = BcdFilelistUIRule.GetEntityListByContionRe(ViewBag.pageNum, ViewBag.numPerPage, "Fl_Numb", out totalRecord, sql, "asc", "View_FileList");
                //总条数
                ViewBag.totalcount = totalRecord;
                //总页数
                ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            }
            return View("ArchiveList", vm);
        }

        /// <summary>  
        /// 判断是否是数字  
        /// </summary>  
        /// <param name="str">字符串</param>  
        /// <returns>bool</returns>  
        public bool IsNumeric(string str)
        {
            if (str == null || str.Length == 0)
                return false;
            System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
            byte[] bytestr = ascii.GetBytes(str);
            foreach (byte c in bytestr)
            {
                if (c < 48 || c > 57)
                {
                    return false;
                }
            }
            return true;
        }
        /// <summary>
        /// 导出所有案卷
        /// </summary>
        /// <param name="pftId"></param>
        public JsonResult ExportAllFile(string pftId)
        {
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                string sql = " (Pft_ID='" + pftId + "' or Pft_PIds like '%" + pftId + "%') ";
                List<BcdFilelistInfo> list = BcdFilelistUIRule.GetEntityListBySql(sql);
                foreach (BcdFilelistInfo info in list)
                {
                    bool isExport = false;//是否导出文件
                    string fileName = "案卷" + info.Fl_Code.Replace("/", "_") + "-" + info.Fl_Numb.ToString("D3");//案卷名
                    string savePath = Server.MapPath("~/Areas/CompletionMaterials/Upload/Temp/" + info.Fl_Item + "/" + info.Fl_FileType + "/" + fileName + ".zip");//存储路径
                    if (System.IO.File.Exists(savePath) == true)//判断文件是否存在
                    {
                        FileInfo fInfo = new FileInfo(savePath);
                        if (info.Fl_OperateTime > fInfo.LastWriteTime)//判断操作时间与文件修改时间
                            isExport = true;
                    }
                    else
                        isExport = true;
                    if (isExport)
                    {
                        List<BcdVolumedirectoryInfo> vlist = BcdVolumedirectoryUIRule.GetEntityListBySql(" Fl_ID='" + info.Fl_ID + "' ");
                        ExportFileToWord(info, vlist, false);
                    }
                }
            });
            dynamic jsonReturn = new ExpandoObject();
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "导出成功"
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "导出失败",
                };
            }

            return new JsonResult()
            {
                Data = jsonReturn
            };
        }

        /// <summary>
        /// 导出案卷目录
        /// </summary>
        /// <returns></returns>
        public void ExportList(string pftId, string code, string numb1, string numb2, string name)
        {
            //工程项目与归档类型与案卷目录对应关系表
            string sql = " (Pft_ID='" + pftId + "' or Pft_PIds like '%" + pftId + "%') ";
            if (code != "")
                sql += " and Fl_Code like '%" + code + "%' ";
            if (numb1 != "")
            {
                if (IsNumeric(numb1))
                    sql += " and Fl_Numb>=" + numb1;
            }
            if (numb2 != "")
            {
                if (IsNumeric(numb2))
                    sql += " and Fl_Numb<=" + numb2;
            }
            if (name != "")
                sql += " and Fl_Item+Fl_FileTitle+Fl_FileName like '%" + name + "%' ";
            List<BcdFilelistInfo> list = BcdFilelistUIRule.GetEntityListBySql(sql);
            string fileName = "案卷目录.docx";
            int i = 0;
            foreach (BcdFilelistInfo info in list)
            {
                i++;
                info.index = i.ToString();
                info.Fl_Code = info.Fl_Code + info.Fl_Numb.ToString("D3");
                info.Fl_FileName = info.Fl_Item + info.Fl_FileTitle + info.Fl_FileName;
            }
            ExportToWord(fileName, list);
        }

    }
}
